package com.zut.chat.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zut.chat.dto.WebSocketMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

/**
 * Redis消息订阅服务
 */
@Slf4j
@Service
@ConditionalOnProperty(name = "spring.redis.enabled", havingValue = "true", matchIfMissing = false)
public class RedisMessageSubscriber {

    @Autowired
    private ChatWebSocketService chatWebSocketService;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 接收Redis消息并广播到WebSocket客户端
     */
    public void receiveMessage(String message) {
        try {
            log.debug("从Redis接收到消息: {}", message);
            WebSocketMessage webSocketMessage = objectMapper.readValue(message, WebSocketMessage.class);
            chatWebSocketService.broadcastMessage(webSocketMessage);
        } catch (Exception e) {
            log.error("处理Redis消息失败: {}", message, e);
        }
    }
}
